<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectTemplate;
use app\app\model\ProjectTemplateRecord;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\Exception;
use think\exception\ValidateException;
use think\facade\Filesystem;

class ProjectEngineeringSample extends BaseController
{
    /**
     * 工程样板导入
     * @return void
     * @throws Exception
     */
    public function import()
    {
        $project_id = input('project_id', '');
        empty($project_id) && $this->error('请传入project_id');

        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'pes', $file['file']);

        $data = (new FileImport())
            ->ExcelImport($file_path . $file_name, 0);

        $id = 0;
        $record_insert_array = [];
        foreach ($data as $k => $v) {
            if ($k == 0) continue;
            if ($k == 1) continue;

            if (!empty($v[2])) {
                $template_insert_array = [
                    'project_id' => $project_id,
                    'area' => $v[1],
                    'template_name' => $v[2],
                    'drawing_require' => $v[4],
                    'acceptance_specification' => $v[5],
                ];
                $id = (new ProjectTemplate())
                    ->insertGetId($template_insert_array);
            }

            if (!empty($v[3]) && $id) {
                $record_insert_array[] = [
                    'process_split' => $v[3],
                    'template_id' => $id,
                ];
            }
        }

        (new ProjectTemplateRecord)->insertAll($record_insert_array);

        $this->success('导入成功');
    }
}